package com.ruoyi.system.service.alipayservice.impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.ruoyi.common.utils.ConstantInfo;
import com.ruoyi.system.domain.alipay.AliPayVO;
import com.ruoyi.system.domain.alipay.AlipayConfig;
import com.ruoyi.system.service.alipayservice.AlipayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@Service
public class AlipayServiceImpl implements AlipayService {
    private static final Object ALIPAY = "";
    private static final Logger logger = LoggerFactory.getLogger(AlipayServiceImpl.class);

    @Autowired
    private AlipayConfig alipayConfig;
    /**
     * @Description: 支付请求
     * */
    @Override
    public Map<String, String> payRequest(String payType, String outTradeNo, BigDecimal totalAmount)throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        switch (PayTypeEnum.valueOf(payType)) {
            case 3://支付宝
                //实例化客户端
                AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getUrl(), alipayConfig.getAppId(),
                        alipayConfig.getRsaPrivateKey(), alipayConfig.getFormat(), alipayConfig.getCharset(),
                        alipayConfig.getAlipayPublicKey(), alipayConfig.getSignType());
                AlipayTradeAppPayRequest aliPayRequest = new AlipayTradeAppPayRequest();
                AlipayTradePayModel model = new AlipayTradePayModel();
                //支付编号
                model.setOutTradeNo(outTradeNo);
                //订单名称
                model.setSubject("某某平台订单支付");
                //支付总金额
                model.setTotalAmount(totalAmount.toString());
                //超时则关闭订单
                model.setTimeoutExpress("30m");
                aliPayRequest.setBizModel(model);
                //异步回调地址
                aliPayRequest.setNotifyUrl(ConstantInfo.ALIPAY_ORDER_CALLBACK);

                AlipayTradeAppPayResponse response = alipayClient.sdkExecute(aliPayRequest);
                map.put("aliPaySdk", response.getBody());
                break;
            default:
                break;
        }
        return map;

    }

    /**
     * @Description: 支付宝支付回调
     */
    @Override
    public AliPayVO aliPayCallBack(HttpServletRequest request) throws Exception {
        //获取支付宝反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset(), alipayConfig.getSignType());
        //校验签名
        if (!signVerified) {
            logger.error("支付宝支付回调签名不正确");
//            throw new RRException(AppWSConstant.RS_MSG_ALIPAY_FALL);
        }
        //校验支付状态
        if (!request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            logger.error("支付宝支付回调支付状态不正确");
//            throw new RRException(AppWSConstant.RS_MSG_ALIPAY_FALL);
        }
        AliPayVO aliPayVo = new AliPayVO();
        //商户订单号
        String outTradeNo = request.getParameter("out_trade_no");
        aliPayVo.setOutTradeNo(outTradeNo);
        //交易状态
        String tradeStatus = request.getParameter("trade_status");
        aliPayVo.setTradeStatus(tradeStatus);
        //资金总额
        String totalAmount = request.getParameter("total_amount");
        aliPayVo.setTotalAmount(totalAmount);
        //卖家支付宝账户
        String sellerId = request.getParameter("seller_id");
        aliPayVo.setSellerId(sellerId);
        //买家支付宝账户
        String buyerLogonId = request.getParameter("buyer_logon_id");
        aliPayVo.setBuyerLogoinId(buyerLogonId);
        //签名方式
        aliPayVo.setSignType(alipayConfig.getSignType());
        //签名
        String sign = request.getParameter("sign");
        aliPayVo.setSign(sign);
        return aliPayVo;
    }

    @Override
    public void aliPayOrderCallBack(AliPayVO aliPayVo) throws Exception {

    }


}
